package com.dsz.apibackend.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsz.apibackend.common.ErrorCode;
import com.dsz.apibackend.enums.InterfaceInfoStatusEnum;
import com.dsz.apibackend.exception.BusinessException;
import com.dsz.apibackend.mapper.UserInterfaceInfoMapper;
import com.dsz.apibackend.model.domain.UserInterfaceInfo;
import com.dsz.apibackend.service.InterfaceInfoService;
import com.dsz.apibackend.service.UserInterfaceInfoService;
import com.dsz.apicommon.model.domain.InterfaceInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;


/**
 * @author dushangzhi
 * @description 针对表【user_interface_info(用户调用接口关系表)】的数据库操作Service实现
 * @createDate 2024-03-28 11:41:15
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {
    @Resource
    private InterfaceInfoService interfaceInfoService;

    /**
     * 接口调用次数+1
     */
    @Override
    public synchronized boolean invokeCount(Long userId, Long interfaceInfoId) {
        //1.校验参数
        userId = Optional.ofNullable(userId).orElse(0L);
        interfaceInfoId = Optional.ofNullable(interfaceInfoId).orElse(0L);
        if (userId <= 0 || interfaceInfoId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.判断接口是否正常
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(interfaceInfoId);
        if (interfaceInfo.getStatus().equals(InterfaceInfoStatusEnum.OFFLINE.getValue())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口已下线");
        }
        //3.判断用户是否可以调用接口
        LambdaQueryWrapper<UserInterfaceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInterfaceInfo::getUserId, userId).eq(UserInterfaceInfo::getInterfaceInfoId, interfaceInfoId);
        UserInterfaceInfo userInterfaceInfo = this.getOne(queryWrapper);
        if (userInterfaceInfo.getStatus() == 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户无权限");
        }
        Integer leftNum = userInterfaceInfo.getLeftNum();
        if (leftNum <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户调用次数已用尽");
        }
        //4.调用次数+1
        userInterfaceInfo.setTotalNum(userInterfaceInfo.getTotalNum() + 1);
        userInterfaceInfo.setLeftNum(leftNum - 1);
        boolean res = this.updateById(userInterfaceInfo);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
        return true;
    }
}




